﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using CNav.Business.Services;
using CNav.Domain;
using CNav.Model;
using CNav.Support;
using WebGrease.Css.Extensions;

namespace CNav.Controllers
{
     [Authorize]
     [AdminAuthorize]
    public class ConsumerController : BaseController
    {
        public ActionResult Create()
        {
            var countryList = Service.Get<IGeneralService>().GetCountries();
            var consumerModel = new ConsumerModel { AddressModel = new AddressModel { CountryList = countryList } };

            return PartialView(consumerModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ConsumerModel consumerModel, AddressModel addressModel)
        {
            if (ModelState.IsValid)
            {
                var consumer = Mapper.Map<Consumer>(consumerModel);
                var address = Mapper.Map<Address>(addressModel);

                var response = Service.Get<IConsumerService>().AddConsumer(consumer, address);
                if (response.Data)
                    return new ContentResult { Content = "OK" };

                response.Error.ForEach(e => ModelState.AddModelError("", e));
            }
            addressModel.CountryList = Service.Get<IGeneralService>().GetCountries();
            consumerModel.AddressModel = addressModel;
            return PartialView(consumerModel);
        }
    }
}